<template>
  <el-drawer :title="isCreate?'添加通道':'编辑通道'" :visible.sync="drawerVisible" :size="'600px'"
             custom-class="data-element-drawer">
    <div class="drawer-body">
      <el-form ref="dataForm" :rules="physicalModelRules" :model="physicalModel" label-width="190px">
        <el-form-item label="端口号" prop="id">
          <div v-if="!isCreate" class="static-text">{{ physicalModel.name }}</div>
          <el-select v-if="isCreate" v-model="physicalModel.id" placeholder="请选择" @change="idChange">
            <el-option v-for="item in ableIds" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="协议" prop="type">
          <div v-if="!isCreate" class="static-text">{{ physicalType }}</div>
          <el-select v-if="isCreate" v-model="physicalModel.type" :disabled="!physicalModel.id" placeholder="请选择"
                     @change="typeChange">
            <el-option v-for="item in physicalTypeOption" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="通道名称" prop="dispName">
          <div v-if="!isCreate" class="static-text">{{ physicalModel.dispName }}</div>
          <el-input v-if="isCreate" v-model="physicalModel.dispName" placeholder="通道名称"/>
        </el-form-item>

        <template v-if="physicalModel.type===4 || physicalModel.type===5 || physicalModel.type===6">
          <el-form-item label="本地IP" prop="localIp">
            <div class="el-input el-input--medium">
              <input type="text" v-model="physicalModel.localIp" placeholder="本地IP" class="el-input__inner">
            </div>
          </el-form-item>
          <el-form-item label="本地子网掩码" prop="localNetmask">
            <el-input v-model="physicalModel.localNetmask" placeholder="本地子网掩码"/>
          </el-form-item>
          <el-form-item label="本地网关地址" prop="localGateway">
            <el-input v-model="physicalModel.localGateway" placeholder="本地网关地址"/>
          </el-form-item>
          <el-form-item v-if="physicalModel.type===5 || physicalModel.type===6" label="本地端口" prop="localPort">
            <el-input v-model="physicalModel.localPort" placeholder="本地端口"/>
          </el-form-item>
        </template>
        <el-form-item v-if="physicalModel.type===3 || physicalModel.type===5" label="本地从机号" prop="localSlaveId">
          <el-select v-model="physicalModel.localSlaveId" placeholder="请选择">
            <el-option v-for="item in 255" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <template v-if="physicalModel.type===1 || physicalModel.type===2 || physicalModel.type===3">
          <el-form-item label="波特率（B）" prop="bts">
            <el-select v-model="physicalModel.bts" placeholder="请选择">
              <el-option v-for="item in btsOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据位（D）" prop="dataBits">
            <el-select v-model="physicalModel.dataBits" placeholder="请选择">
              <el-option v-for="item in dataBitsOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="停止位（S）" prop="stopBits">
            <el-select v-model="physicalModel.stopBits" placeholder="请选择">
              <el-option v-for="item in stopBitsOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="校验位（P）" prop="parity">
            <el-select v-model="physicalModel.parity" placeholder="请选择">
              <el-option v-for="item in parityOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="流控制（F）" prop="flowControl">
            <el-select v-model="physicalModel.flowControl" placeholder="请选择">
              <el-option v-for="item in flowControlOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </template>

        <template v-if="physicalModel.type===1 || physicalModel.type===6">
          <el-form-item label="端口重置周期（秒）" prop="restartTimeout">
            <el-input v-model.number="physicalModel.restartTimeout" type="number" placeholder="端口重置周期"/>
            <div class="tips-text">大于设定时间无接收数据重置端口</div>
          </el-form-item>
          <el-form-item label="端口故障周期（秒）" prop="faultTimer">
            <el-input v-model.number="physicalModel.faultTimer" type="number" placeholder="端口故障周期"/>
            <div class="tips-text">大于设定时间没有数据标记通道故障</div>
          </el-form-item>
        </template>

        <template v-if="physicalModel.type!==1&&physicalModel.type!=6">
          <template v-if="physicalModel.type!=3&&physicalModel.type!=5">
            <el-form-item label="单次数据扫描周期" prop="scanTimer">
              <el-select v-model="physicalModel.scanTimer" placeholder="请选择">
                <el-option v-for="item in scanTimerOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="单次数据扫描超时" prop="scanTimeout">
              <el-select v-model="physicalModel.scanTimeout" placeholder="请选择">
                <el-option v-for="item in scanTimeoutOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="单次数据扫描重试" prop="retry">
              <el-select v-model="physicalModel.retry" placeholder="请选择">
                <el-option v-for="item in retryOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="最大故障重试次数" prop="faultRetries">
              <el-input v-model.number="physicalModel.faultRetries" type="number" placeholder="最大故障重试次数"/>
              <div class="tips-text">大于重试次数标记通道故障</div>
            </el-form-item>
          </template>
          <el-form-item label="故障状态扫描周期" prop="faultScanTimer">
            <el-select v-model.number="physicalModel.faultScanTimer" type="number" placeholder="请选择">
              <el-option v-for="item in faultScanTimerOptions" :key="item.value" :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </template>

        <el-form-item label="故障数据处理" prop="faultDataHandle">
          <el-select v-model="physicalModel.faultDataHandle" placeholder="请选择">
            <el-option v-for="item in faultDataHandleOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="drawer-footer">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" :loading="isSubmitLoading" @click="save()">提交</el-button>
    </div>
  </el-drawer>
</template>
<script>
  import {
    updatePhysicalPort,
    getPortIdList,
    getPortTypeById,
    createPhysicalPort
  } from "@/api/physicalPort";
  import {
    physicalTypeOptions,
    flowControlOptions,
    btsOptions,
    dataBitsOptions,
    stopBitsOptions,
    parityOptions,
    scanTimerOptions,
    scanTimeoutOptions,
    retryOptions,
    faultScanTimerOptions,
    faultDataHandleOptions
  } from "@/utils/enums.js";

  export default {
    props: {},
    data() {
      return {
        physicalTypeOptions,
        flowControlOptions,
        btsOptions,
        dataBitsOptions,
        stopBitsOptions,
        parityOptions,
        scanTimerOptions,
        scanTimeoutOptions,
        retryOptions,
        faultScanTimerOptions,
        faultDataHandleOptions,
        physicalTypeOption: [],
        physicalModel: {},
        ableIds: [],
        drawerVisible: false,
        isSubmitLoading: false,
        isCreate: false,
        physicalModelRules: {
          id: [{ required: true, trigger: "change", message: "请选择端口号" }],
          type: [{ required: true, trigger: "change", message: "请选择协议" }],
          dispName: [
            { required: true, trigger: "blur", message: "请输入通道名称" }
          ],
          localSlaveId: [
            { required: true, trigger: "blur", message: "请输入本地从机号" }
          ],
          localPort: [
            { required: true, trigger: "blur", message: "请输入本地端口" }
          ],
          bts: [{ required: true, trigger: "change", message: "请选择波特率" }],
          dataBits: [
            { required: true, trigger: "change", message: "请选择数据位" }
          ],
          stopBits: [
            { required: true, trigger: "change", message: "请选择停止位" }
          ],
          flowControl: [
            { required: true, trigger: "change", message: "请选择流控制" }
          ],
          parity: [
            { required: true, trigger: "change", message: "请选择校验位" }
          ],
          restartTimeout: [
            { required: true, trigger: "blur", message: "请输入端口重置周期" }
          ],
          faultTimer: [
            { required: true, trigger: "blur", message: "请输入端口故障周期" }
          ],
          scanTimer: [
            {
              required: true,
              trigger: "change",
              message: "请选择单次数据扫描周期"
            }
          ],
          scanTimeout: [
            {
              required: true,
              trigger: "change",
              message: "请选择单次数据扫描超时"
            }
          ],
          retry: [
            {
              required: true,
              trigger: "change",
              message: "请选择单次数据扫描重试"
            }
          ],
          faultRetries: [
            { required: true, trigger: "blur", message: "请输入最大故障重试次数" }
          ],
          faultScanTimer: [
            {
              required: true,
              trigger: "change",
              message: "请选择故障状态扫描周期"
            }
          ],
          faultDataHandle: [
            { required: true, trigger: "change", message: "请选择故障数据处理" }
          ],
          localIp: [{ required: true, trigger: "blur", message: "请输入本地IP" }],
          localNetmask: [
            { required: true, trigger: "blur", message: "请输入本地子网掩码" }
          ]
        }
      };
    },
    computed: {
      physicalType: function () {
        let returnVal = "";
        if (Object.keys(this.physicalModel).length) {
          switch (this.physicalModel.type) {
            case 1:
              returnVal = "DCS-COM";
              break;
            case 2:
              returnVal = "ModbusRTU-主站";
              break;
            case 3:
              returnVal = "ModbusRTU-从站";
              break;
            case 4:
              returnVal = "ModbusTCP-主站";
              break;
            case 5:
              returnVal = "ModbusTCP-从站";
              break;
            case 6:
              returnVal = "DCS-TCP";
              break;
            case 8:
              returnVal = 'Webservice';
              break;
            case 9:
              returnVal = 'KafkaConsumer';
              break;
            default:
              returnVal = this.physicalModel.type;
              break;
          }
        }
        return returnVal;
      }
    },
    watch: {
    },
    mounted() {
    },
    methods: {
      show(row) {
        this.resetModal();
        this.isSubmitLoading = false;
        if (row) {
          this.physicalModel = row;
          this.isCreate = false;
        } else {
          this.isCreate = true;
          this.getPortIdList();
        }
        this.drawerVisible = true;
      },
      getPortIdList() {
        this.isSubmitLoading = true;
        // 可用id
        getPortIdList().then(result => {
          if (result.length) {
            this.ableIds = result;
          } else if (result.length === 0) {
            this.$message({
              message: "通道数量已满",
              type: "warning"
            });
          }
          this.isSubmitLoading = false;
        });
      },
      idChange(id) {
        this.isSubmitLoading = true;
        // 可用id
        getPortTypeById(id).then(result => {
          if (result.length) {
            this.physicalTypeOption = this.physicalTypeOptions.filter(
              m => result.indexOf(m.value) !== -1
            );
          }
          this.isSubmitLoading = false;
        });
        const local = this.ableIds.filter(m => m.id === id);
        this.physicalModel.localIp = local[0].localIp;
      },
      typeChange(val) {
        if (val === 4 || val === 5 || val === 6) {
          this.physicalModel.bts = undefined;
          this.physicalModel.dataBits = undefined;
          this.physicalModel.stopBits = undefined;
          if (val === 6) {
            this.physicalModel.localPort = '4321';
          } else {
            this.physicalModel.localPort = '502';
          }
        }
        this.clearValidate();
      },
      clearValidate() {
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      },
      resetModal() {
        this.physicalModel = {
          localSlaveId: 1,
          localPort: "502",
          localNetmask: "255.255.255.0",
          bts: 9600,
          dataBits: 8,
          parity: 0,
          stopBits: 1,
          flowControl: 0,
          scanTimer: 1,
          scanTimeout: 200,
          restartTimeout: 1800,
          faultTimer: 3600,
          retry: 1,
          faultDataHandle: 1,
          faultScanTimer: 30,
          faultRetries: 25
        };
        this.clearValidate();
      },
      save() {
        this.isSubmitLoading = true;
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            //
            if (this.isCreate) {
              createPhysicalPort(this.physicalModel)
                .then(() => {
                  this.success();
                })
                .catch(() => {
                  this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
                });
            } else {
              updatePhysicalPort(this.physicalModel)
                .then(() => {
                  this.success();
                })
                .catch(() => {
                  this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
                });
            }
          } else {
            this.isSubmitLoading = false;
            this.$message({
              message: this.$t("formIsNotValidMessage"),
              type: "warning"
            });
          }
        });
      },
      success() {
        this.$message({
          message: this.isCreate ? "添加成功" : "编辑成功",
          type: "success"
        });
        this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
        this.close();
        this.$emit("save", this.isCreate);
      },
      close() {
        this.drawerVisible = false;
        this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
      }
    }
  };
</script>

<style lang="scss">
  .data-element-drawer {
    .el-drawer__body {
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }

    .drawer-body {
      flex: 1;
      overflow: auto;
      padding-bottom: 56px;

      .el-input {
        max-width: 360px;
      }

      .el-select {
        width: 360px;
      }
    }

    .drawer-footer {
      padding: 10px;
      background-color: #eef1f6;
      text-align: right;

      button {
        min-width: 100px;
      }
    }
  }

  .static-text {
    display: inline-block;
  }

  .tips-text {
    display: inline-block;
    font-size: small;
    margin-left: 5px;
    color: #999999;
  }
</style>
